/**
 * Copyright (C) 2021 - 2031 O-Cubes Co., Ltd.
 */

/****************************************************************
 *  @file    saradc.c
 *  @brief   saradc driver
 *  @version v1.0
 *  @date    12  Sep. 2023
 *  @author  liusg
 ****************************************************************/
#include "sdadc.h"

void sdadc_bais_pwr_en(bool enable)
{
	if (enable == true) {
		SDADC->ADC_CTRL &= ~SDADC_BAIS_PWR_ON;
	} else {
		SDADC->ADC_CTRL |= SDADC_BAIS_PWR_ON;
	}
}

void sdadc_ref_pwr_en(bool enable)
{
	if (enable == true) {
		SDADC->ADC_CTRL &= ~SDADC_REF_PWR_ON;
	} else {
		SDADC->ADC_CTRL |= SDADC_REF_PWR_ON;
	}
}

void sdadc_chans_pwr_en(bool enable)
{
	SDADC->CHAN_PWR = (enable ? SDADC_CHANS_PWR_ON : SDADC_CHANS_PWR_OFF);
}

void sdadc_chans_en(bool enable)
{
	SDADC->CHAN_EN = (enable ? SDADC_CHANS_ENABLE : 0);
}

void sdadc_enable(bool enable)
{
	SDADC->ADC_ENBALE = (enable ? SDADC_ENABLE : 0);
}

void sdadc_gain_cfg(sdadc_chan chan, uint8_t gain)
{
	uint32_t id = chan * SDADC_GAIN_CFG_BIT_SIZE / 32;
	uint32_t offset = chan * SDADC_GAIN_CFG_BIT_SIZE % 32;
	SDADC->CHAN_GAIN[id] |= gain << offset;
}

void sdadc_phase_en(sdadc_phase phase, bool enable)
{
	if (enable) {
		SDADC->ADC_PHASE[phase] |= SDADC_PHASE_ENABLE;
	} else {
		SDADC->ADC_PHASE[phase] &= ~SDADC_PHASE_ENABLE;
	}
}

void sdadc_phase_cfg(sdadc_phase phase, uint8_t u_delay, uint8_t ih_delay, uint8_t im_delay,
                         uint8_t il_delay)
{
	SDADC->ADC_PHASE[phase] &= (~SDADC_PHASE_UDELAY_MASK) | (~SDADC_PHASE_IHDELAY_MASK) |
                               (~SDADC_PHASE_IMDELAY_MASK) | (~SDADC_PHASE_ILDELAY_MASK);
	SDADC->ADC_PHASE[phase] |= (u_delay << SDADC_PHASE_UDELAY_OFF) |
                               (ih_delay << SDADC_PHASE_IHDELAY_OFF) |
                               (im_delay << SDADC_PHASE_IMDELAY_OFF) |
                               (il_delay << SDADC_PHASE_ILDELAY_OFF);
}

void sdadc_zl_phase_en(bool enable)
{
	if (enable) {
		SDADC->ZL_PHASE |= SDADC_ZL_PHASE_ENABLE;
	} else {
		SDADC->ZL_PHASE &= ~SDADC_ZL_PHASE_ENABLE;
	}
}

void sdadc_zl_phase_cfg(uint8_t ih_delay, uint8_t im_delay, uint8_t il_delay)
{
	SDADC->ZL_PHASE &= (~SDADC_PHASE_IHDELAY_MASK) | (~SDADC_PHASE_IMDELAY_MASK) | (~SDADC_PHASE_ILDELAY_MASK);
	SDADC->ZL_PHASE |= (ih_delay << SDADC_PHASE_IHDELAY_OFF) | (im_delay << SDADC_PHASE_IMDELAY_OFF) |
                       (il_delay << SDADC_PHASE_ILDELAY_OFF);
}

void sdadc_init(void)
{
	sdadc_chans_pwr_en(true);
	sdadc_ref_pwr_en(true);
	sdadc_bais_pwr_en(true);
	sdadc_chans_en(true);
	sdadc_enable(true);
}

